<template>
  <div class="post-form">
    <el-form ref="formRef" :model="formData" :rules="rules">
      <!-- 富文本编辑器 -->
      <el-form-item prop="content">
        <div class="editor-wrapper">
          <div class="editor-container">
            <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
              style="border-bottom: 1px solid var(--el-border-color)"
              class="editor-toolbar"
            />
            <Editor
              v-model="formData.content"
              :defaultConfig="editorConfig"
              mode="default"
              class="editor-body"
              style="height: 300px; overflow-y: hidden"
              @onCreated="handleEditorCreated"
              @onChange="handleEditorChange"
            />
          </div>
        </div>
      </el-form-item>

      <!-- 图片/视频上传 -->
      <el-form-item label="添加图片/视频" prop="media">
        <ImageVideoUpload
          v-model="formData.media"
          :limit="9"
          :maxSize="10 * 1024 * 1024"
          @exceed="handleMediaExceed"
        />
      </el-form-item>

      <!-- 话题选择 -->
      <el-form-item label="添加话题" prop="topics">
        <el-select
          v-model="formData.topics"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="选择或创建话题"
          class="w-full"
        >
          <el-option
            v-for="topic in hotTopics"
            :key="topic.id"
            :label="topic.name"
            :value="topic.id"
          />
        </el-select>
      </el-form-item>

      <!-- 位置信息 -->
      <el-form-item label="添加位置" prop="location">
        <el-input
          v-model="formData.location"
          placeholder="输入位置信息"
          class="w-full"
        >
          <template #prefix>
            <el-icon><Location /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 权限设置 -->
      <el-form-item label="可见范围" prop="visibility">
        <el-radio-group v-model="formData.visibility">
          <el-radio label="public">所有人可见</el-radio>
          <el-radio label="friends">仅好友可见</el-radio>
          <el-radio label="private">仅自己可见</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <div class="flex justify-end gap-4">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            发布
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, shallowRef, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { Location } from "@element-plus/icons-vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import ImageVideoUpload from "@/components/global/ImageVideoUpload.vue";

const props = defineProps({
  hotTopics: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["cancel", "submit"]);

// 表单数据
const formData = ref({
  content: "",
  media: [],
  topics: [],
  location: "",
  visibility: "public",
});

// 表单校验规则
const rules = {
  content: [
    { required: true, message: "请输入动态内容", trigger: "blur" },
    {
      min: 1,
      max: 10000,
      message: "内容长度在1到10000个字符",
      trigger: "blur",
    },
  ],
};

// 编辑器实例
const editorRef = shallowRef();

// 编辑器配置
const editorConfig = {
  placeholder: "分享你的旅行故事...",
  autoFocus: false,
  scroll: true,
  MENU_CONF: {
    uploadImage: {
      server: "/api/upload/image",
      fieldName: "file",
      maxFileSize: 5 * 1024 * 1024,
      maxNumberOfFiles: 10,
      allowedFileTypes: ["image/*"],
      metaWithUrl: true,
      customInsert(res, insertFn) {
        insertFn(res.url, res.alt, res.href);
      },
    },
  },
};

// 工具栏配置
const toolbarConfig = {
  toolbarKeys: [
    "headerSelect",
    "bold",
    "italic",
    "underline",
    "through",
    "color",
    "bgColor",
    "|",
    "bulletedList",
    "numberedList",
    "todo",
    "|",
    "emotion",
    "insertLink",
    "|",
    "undo",
    "redo",
  ],
};

// 处理编辑器创建
const handleEditorCreated = (editor) => {
  editorRef.value = editor;
};

// 处理编辑器内容变化
const handleEditorChange = (editor) => {
  formData.value.content = editor.getHtml();
};

// 处理媒体超出限制
const handleMediaExceed = () => {
  ElMessage.warning("最多只能上传9个文件");
};

// 处理取消
const handleCancel = () => {
  emit("cancel");
};

// 提交状态
const submitting = ref(false);

// 表单引用
const formRef = ref(null);

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    submitting.value = true;

    // 构建提交数据
    const postData = {
      ...formData.value,
      content: editorRef.value?.getHtml() || "",
    };

    emit("submit", postData);
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};

// 组件销毁前清理编辑器实例
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style lang="scss" scoped>
.post-form {
  .editor-wrapper {
    @apply w-full;

    .editor-container {
      @apply border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden;

      .editor-toolbar {
        @apply bg-white dark:bg-gray-800;
      }

      .editor-body {
        @apply bg-white dark:bg-gray-800;
      }
    }
  }
}

:deep(.w-e-text-container) {
  @apply bg-white dark:bg-gray-800;

  [data-slate-editor] {
    @apply text-gray-900 dark:text-gray-100;
  }
}

:deep(.w-e-toolbar) {
  @apply bg-white dark:bg-gray-800 border-0;

  .w-e-bar-item {
    @apply text-gray-700 dark:text-gray-300;

    &:hover {
      @apply bg-gray-100 dark:bg-gray-700;
    }

    .w-e-icon {
      @apply text-gray-700 dark:text-gray-300;
    }
  }

  .w-e-bar-divider {
    @apply bg-gray-200 dark:bg-gray-700;
  }

  .w-e-bar-item-active {
    @apply bg-primary-50 dark:bg-primary-900;
  }
}

:deep(.w-e-text-placeholder) {
  @apply text-gray-400 dark:text-gray-500;
}

:deep(.w-e-panel) {
  @apply bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700;

  .w-e-panel-tab-title {
    @apply text-gray-900 dark:text-gray-100;
  }

  .w-e-panel-tab-content {
    @apply text-gray-900 dark:text-gray-100;
  }
}

:deep(.el-form-item) {
  @apply mb-6;

  .el-form-item__label {
    @apply dark:text-gray-300;
  }

  .el-input__wrapper {
    @apply dark:bg-gray-700 dark:border-gray-600;
  }

  .el-input__inner {
    @apply dark:text-gray-100;
  }

  .el-textarea__inner {
    @apply dark:bg-gray-700 dark:text-gray-100 dark:border-gray-600;
  }
}

.image-uploader {
  .upload-area {
    @apply border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-lg 
           hover:border-primary-500 dark:hover:border-primary-500 
           transition-colors duration-300 cursor-pointer;

    .upload-placeholder {
      @apply h-48 flex flex-col items-center justify-center text-gray-400 dark:text-gray-500;
    }
  }

  :deep(.el-upload-list) {
    @apply mt-4;

    .el-upload-list__item {
      @apply dark:bg-gray-700 dark:text-gray-100 dark:border-gray-600;

      .el-icon {
        @apply dark:text-gray-400;
      }

      &:hover {
        @apply dark:bg-gray-600;
      }
    }
  }
}
</style>
